package com.zmn.plat.services.impl.key;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.utils.number.PECodeUtil;
import com.zmn.common.utils.number.RandomUtil;
import com.zmn.plat.model.entity.key.BaseKey;
import com.zmn.plat.persistence.interfaces.key.KeyDao;
import com.zmn.plat.services.interfaces.key.KeyService;

/**
 * @author duanzuocai
 * @version v1.0
 * @since 2019/1/18 14:50
 */
@Service
public class KeyServiceImpl implements KeyService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    KeyDao keyDao;

    @Override
    public String findOneRandomKey(Integer type) {
        int num = count(type);
        if (num < SECURITY_LINE_CODE) {
            logger.info("[zmn]-get: 保修卡随机Code剩余:{}不足:{}个, 开始创建:{}个", num, KeyService.SECURITY_LINE_CODE, KeyService.SECURITY_LINE_JOB);
            create(SECURITY_LINE_JOB, type);
        }

        return keyDao.findOneRandomKey(type);
    }

    @Override
    public int count(int type) {
        return keyDao.count(type);
    }

    @Override
    public void create(Integer num, Integer type) {
        List<BaseKey> list = new ArrayList<>();

        Date date = new Date();
        for (int i = 0; i < num; i++) {
            long randomLong = RandomUtil.getRandomLong(MIN_KEY, MAX_KEY);
            String random = PECodeUtil.encode38(BigInteger.valueOf(randomLong));
            list.add(new BaseKey(type, GlobalConsts.NO, random, BigInteger.valueOf(randomLong), date));
        }

        keyDao.create(list);
    }
}
